﻿using System.Net;
using System.Xml;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marbles.Core.Web.Syndication
{
    public class FeedReader
    {
        internal XmlDocument Document { get { return doc; } }

        public FeedType FeedType { get { return this._FeedType; } }

        private FeedType _FeedType = FeedType.Unknown;
        private XmlDocument doc = null;

        public FeedReader(string Filename)
        {
            this._FeedType = FeedType.Unknown;
            doc = FeedHelper.GetFeedXml(Filename);
        }

        public FeedReader(Uri FeedUrl)
        {
            this._FeedType = FeedType.Unknown;
            doc = FeedHelper.GetFeedXml(FeedUrl);
        }

        public FeedReader(Uri FeedUrl, WebProxy Proxy)
        {
            this._FeedType = FeedType.Unknown;
            doc = FeedHelper.GetFeedXml(FeedUrl, Proxy);
        }

        public FeedReader(Uri FeedUrl, string Host, string Username, string Password)
        {
            this._FeedType = FeedType.Unknown;
            doc = FeedHelper.GetFeedXml(FeedUrl, Host, Username, Password);
        }

        public FeedReader(System.IO.Stream FeedStream)
        {
            this._FeedType = FeedType.Unknown;
            doc = new XmlDocument();
            StreamReader sr = new StreamReader(FeedStream);
            doc.LoadXml(sr.ReadToEnd());
            sr.Close();
        }

        public IFeed Read()
        {
            IFeed feed = null;
            if (Document == null) { return null; }

            XmlNodeList nodes = Document.GetElementsByTagName("rss");

            if (nodes.Count > 0) { this._FeedType = FeedType.RSS; return RSS.RSSFeedReader.Parse(Document); }

            nodes = null;
            nodes = Document.GetElementsByTagName("feed");
            if (nodes.Count > 0) { this._FeedType = FeedType.Atom; return Atom.AtomFeedReader.Parse(Document); }

            this._FeedType = FeedType.Unknown;
            return feed;
        }
    }

    public enum FeedType
    {
        Unknown, RSS, Atom
    }
}
